import requests

# 发送GET请求
response = requests.get('https://www.example.com')

# 查看响应状态码
print(f"状态码: {response.status_code}")

# 查看响应内容
print(f"网页内容前100字符: {response.text[:100]}")

# 查看响应头
print("响应头:")
for key, value in response.headers.items():
    print(f"{key}: {value}")




import requests

# 定义查询参数
params = {
    'q': 'Python编程',
    'page': 1,
    'limit': 10
}

# 发送带参数的GET请求
response = requests.get('https://httpbin.org/get', params=params)

# 查看实际请求的URL
print(f"实际请求URL: {response.url}")

# 解析JSON响应
data = response.json()
print("\n返回的JSON数据:")
print(data)




import requests

# 定义POST数据
payload = {
    'username': 'testuser',
    'password': 'testpass'
}

# 发送POST请求
response = requests.post('https://httpbin.org/post', data=payload)

# 解析并打印JSON响应
print(response.json())





import requests

# 获取JSON API数据
response = requests.get('https://api.github.com/events')

# 检查请求是否成功
if response.status_code == 200:
    events = response.json()
    print(f"获取到{len(events)}个事件")
    print("\n第一个事件详情:")
    print(events[0])
else:
    print(f"请求失败，状态码: {response.status_code}")

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}

response = requests.get('https://www.example.com', headers=headers)
print(response.text[:200])  # 打印前200个字符




import matplotlib.pyplot as plt

# 准备数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# 创建图形
plt.figure(figsize=(8, 4))  # 设置图形大小

# 绘制折线图
plt.plot(x, y, marker='o', linestyle='--', color='b', label='线性增长')

# 添加标题和标签
plt.title('基础折线图示例')
plt.xlabel('X轴')
plt.ylabel('Y轴')

# 添加图例
plt.legend()

# 显示网格
plt.grid(True)

# 显示图形
plt.show()





import matplotlib.pyplot as plt

# 数据准备
categories = ['苹果', '香蕉', '橙子', '梨']
quantities = [45, 30, 55, 20]

# 创建柱状图
plt.figure(figsize=(8, 5))
bars = plt.bar(categories, quantities, color=['red', 'yellow', 'orange', 'green'])

# 添加数据标签
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height}',
             ha='center', va='bottom')

# 添加标题和标签
plt.title('水果销量')
plt.xlabel('水果种类')
plt.ylabel('销量(公斤)')

# 显示图形
plt.show()












import matplotlib.pyplot as plt

# 数据准备
labels = ['娱乐', '餐饮', '交通', '购物', '其他']
sizes = [15, 30, 10, 35, 10]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']

# 创建饼图
plt.figure(figsize=(8, 6))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)

# 添加标题
plt.title('月度支出比例')

# 保证饼图是圆形
plt.axis('equal')

# 显示图形
plt.show()

import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)

# 创建散点图
plt.figure(figsize=(8, 6))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')

# 添加颜色条
plt.colorbar()

# 添加标题和标签
plt.title('随机散点图')
plt.xlabel('X值')
plt.ylabel('Y值')

# 显示图形
plt.show()







import requests
import matplotlib.pyplot as plt
from datetime import datetime

# 1. 爬取COVID-19数据（示例API，可能需要替换为真实API）
url = "https://disease.sh/v3/covid-19/historical/all?lastdays=30"
response = requests.get(url)
data = response.json()

# 2. 处理数据
cases = data['cases']
dates = list(cases.keys())
values = list(cases.values())

# 将日期字符串转换为datetime对象
dates = [datetime.strptime(date, "%m/%d/%y") for date in dates]

# 3. 绘制图表
plt.figure(figsize=(12, 6))

# 绘制折线图
plt.plot(dates, values, 'r-', marker='o', label='每日新增病例')

# 格式化图表
plt.title('全球COVID-19新增病例趋势 (最近30天)')
plt.xlabel('日期')
plt.ylabel('新增病例数')
plt.xticks(rotation=45)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()

# 自动调整布局
plt.tight_layout()

# 显示图表
plt.show()

import requests


def get_weather(api_key, location):
    """
    获取心知天气API数据
    :param api_key: 你的API密钥
    :param location: 城市名，如"北京"
    :return: 天气数据字典
    """
    url = "https://api.seniverse.com/v3/weather/now.json"
    params = {
        'key': api_key,
        'location': location,
        'language': 'zh-Hans',
        'unit': 'c'
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        weather_data = response.json()
        return weather_data
    except requests.exceptions.RequestException as e:
        print(f"获取天气数据出错: {e}")
        return None


def print_weather(weather_data):
    """打印天气信息"""
    if not weather_data or 'results' not in weather_data:
        print("未获取到有效的天气数据")
        return

    result = weather_data['results'][0]
    location = result['location']['name']
    weather = result['now']['text']
    temperature = result['now']['temperature']
    update_time = result['last_update'][:-6].replace('T', ' ')

    print("\n=== 当前天气状况 ===")
    print(f"城市: {location}")
    print(f"天气: {weather}")
    print(f"温度: {temperature}°C")
    print(f"更新时间: {update_time}")


# 使用示例（需要替换为你的API密钥）
API_KEY = "YOUR_API_KEY"  # 请到心知天气官网申请免费API
CITY = "北京"

weather_data = get_weather(API_KEY, CITY)
if weather_data:
    print_weather(weather_data)

import requests


def get_openweather(api_key, city):
    """
    获取OpenWeatherMap天气数据
    :param api_key: 你的API密钥
    :param city: 城市名
    :return: 天气数据字典
    """
    url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        'q': city,
        'appid': api_key,
        'units': 'metric',
        'lang': 'zh_cn'
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"获取天气数据出错: {e}")
        return None


def print_openweather(data):
    """打印OpenWeatherMap天气信息"""
    if not data:
        return

    print("\n=== 当前天气状况 ===")
    print(f"城市: {data['name']}")
    print(f"天气: {data['weather'][0]['description']}")
    print(f"当前温度: {data['main']['temp']}°C")
    print(f"体感温度: {data['main']['feels_like']}°C")
    print(f"最低温度: {data['main']['temp_min']}°C")
    print(f"最高温度: {data['main']['temp_max']}°C")
    print(f"湿度: {data['main']['humidity']}%")
    print(f"风速: {data['wind']['speed']} m/s")


# 使用示例（需要替换为你的API密钥）
OWM_API_KEY = "YOUR_OPENWEATHERMAP_API_KEY"  # 到OpenWeatherMap官网申请
CITY = "Shanghai"

weather_data = get_openweather(OWM_API_KEY, CITY)
if weather_data:
    print_openweather(weather_data)









import matplotlib.pyplot as plt

# 模拟学生成绩数据
scores = [78, 85, 92, 65, 70, 88, 76, 81, 95, 68,
          72, 89, 83, 77, 84, 90, 67, 73, 86, 79]

# 创建分数段分布
bins = [50, 60, 70, 80, 90, 100]
score_ranges = ['50-59', '60-69', '70-79', '80-89', '90-100']
distribution = [0] * len(score_ranges)

# 统计各分数段人数
for score in scores:
    for i in range(len(bins)-1):
        if bins[i] <= score < bins[i+1]:
            distribution[i] += 1
            break
    if score == 100:
        distribution[-1] += 1

# 设置中文字体显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # Mac
plt.rcParams['axes.unicode_minus'] = False

# 创建折线图
plt.figure(figsize=(10, 6))
plt.plot(score_ranges, distribution, marker='o', linestyle='-', color='b', linewidth=2)

# 添加标题和标签
plt.title('学生成绩分布', fontsize=16)
plt.xlabel('分数段', fontsize=12)
plt.ylabel('人数', fontsize=12)

# 添加数据标签
for x, y in zip(score_ranges, distribution):
    plt.text(x, y+0.2, str(y), ha='center', va='bottom', fontsize=12)

# 设置网格和y轴范围
plt.grid(True, linestyle='--', alpha=0.6)
plt.ylim(0, max(distribution)+1)

# 显示图表
plt.tight_layout()
plt.show()









import matplotlib.pyplot as plt
import numpy as np

# 模拟班级成绩数据
np.random.seed(42)
class_a = np.random.normal(75, 10, 30).astype(int)
class_b = np.random.normal(85, 8, 30).astype(int)

# 创建分数段分布
bins = [50, 60, 70, 80, 90, 101]
score_ranges = ['50-59', '60-69', '70-79', '80-89', '90-100']

def calculate_distribution(scores):
    hist, _ = np.histogram(scores, bins=bins)
    return hist

dist_a = calculate_distribution(class_a)
dist_b = calculate_distribution(class_b)

# 设置图形
plt.figure(figsize=(12, 6))

# 绘制折线图
line_a, = plt.plot(score_ranges, dist_a, 'b-o', label='班级A', linewidth=2)
line_b, = plt.plot(score_ranges, dist_b, 'r-s', label='班级B', linewidth=2)

# 计算并绘制平均线
avg_a = np.mean(class_a)
avg_b = np.mean(class_b)
plt.axhline(avg_a, color='blue', linestyle='--', alpha=0.3)
plt.axhline(avg_b, color='red', linestyle='--', alpha=0.3)

# 添加文本说明
plt.text(4.5, avg_a, f'班级A平均分: {avg_a:.1f}', color='blue', va='center')
plt.text(4.5, avg_b, f'班级B平均分: {avg_b:.1f}', color='red', va='center')

# 添加标题和标签
plt.title('两个班级成绩分布对比', fontsize=16)
plt.xlabel('分数段', fontsize=12)
plt.ylabel('人数', fontsize=12)
plt.legend(fontsize=12)

# 添加数据标签
for i, (a, b) in enumerate(zip(dist_a, dist_b)):
    plt.text(i, a+0.3, str(a), ha='center', color='blue')
    plt.text(i, b+0.3, str(b), ha='center', color='red')

# 设置网格和y轴范围
plt.grid(True, linestyle=':', alpha=0.5)
plt.ylim(0, max(max(dist_a), max(dist_b)) + 2)

# 显示图表
plt.tight_layout()
plt.show()











